package com.woniu.service.impl;

import com.woniu.entity.Menu;
import com.woniu.mapper.MenuMapper;
import com.woniu.service.MenuService;
import com.woniu.util.ResponseData;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {
    @Resource
    private MenuMapper menuMapper;

    /**
     * 根据登录员工的id查询员工需要显示的列表
     * 把数据转换为一级菜单中包含二级菜单的结构
     * 1：先找出所有的父菜单  List<Menu>
     * 2：循环父菜单，去所有菜单的集合中找对应的子菜单（父菜单的id = 菜单的parentId）
    * */
    @Override
    public List<Menu> queryMenus(Integer employeeId) {
        List<Menu> menus = menuMapper.queryEmployeeMenu(employeeId);

        // 找出所有的父菜单
        List<Menu> parentMenu = menus.stream()
                .filter(e -> e.getParentId().equals(-1))
                .collect(Collectors.toList());

        for (Menu pMenu : parentMenu) {
            List<Menu> childrenMenu = new ArrayList<>();
            for (Menu menu : menus) {
                if (pMenu.getId().equals(menu.getParentId())) {
                    // 证明该菜单是父菜单的子菜单
                    childrenMenu.add(menu);
                }
            }
            pMenu.setChildrenMenu(childrenMenu);
        }

        return parentMenu;
    }
}
